package admin

import (
	"net/http"

	"gitee.com/cxssang/goframe/lib/sql"

	. "gitee.com/cxssang/genealogy/act"
)

func init() {
	HandleFunMap["/admin/setting"] = func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case "GET":
			sq := sql.New()
			rows, err := sq.Select("setting", sql.NewWhere().Add("key in('name','source','profile')"), 0, 0, "*", "").FetchAll()
			if err != nil {
				DisplayError(w, err.Error())
				return
			}
			data := map[string]interface{}{
				"name":    "",
				"source":  "",
				"profile": "",
			}
			for _, row := range rows {
				data[row.Get("key")] = row.Get("value")
			}
			row, err := sq.Select("members", sql.NewWhere().Add("parent_id=0"), 0, 0, "*", "").FetchOne()
			if row == nil {
				row = &sql.Row{}
				for _, key := range []string{"name", "spouse", "birth", "remark"} {
					row.Set(key, "")
				}
			}
			data["ancestors"] = row
			Display(w, r, "admin/setting", data)
		case "POST":
			name := r.FormValue("name")
			ancestors_name := r.FormValue("ancestors_name")
			spouse := r.FormValue("spouse")
			birth := r.FormValue("birth")
			remark := r.FormValue("remark")
			source := r.FormValue("source")
			profile := r.FormValue("profile")
			if CheckEmpty(w, name, "族谱名称不能为空", ancestors_name, "先祖姓名不能为空") {
				return
			}
			sq := sql.New()
			st, err := sq.Raw("replace into setting(key,value) values(?,?)").Prepare()
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			_, _ = st.Exec("name", name)
			_, _ = st.Exec("source", source)
			_, _ = st.Exec("profile", profile)
			count, err := sq.Count("members", sql.NewWhere().Add("parent_id=0"), "*")
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			if count == 0 {
				_, err = sq.Insert("members", map[string]interface{}{
					"name":      ancestors_name,
					"spouse":    spouse,
					"birth":     birth,
					"remark":    remark,
					"parent_id": 0,
				}).Exec()
			} else {
				_, err = sq.Update("members", sql.NewWhere().Add("parent_id=0"), map[string]interface{}{
					"name":   ancestors_name,
					"spouse": spouse,
					"birth":  birth,
					"remark": remark,
				}).Exec()
			}
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			JsonSuccess(w, nil)
		}
	}
}
